package com.nervenets.web.config;

import com.nervenets.utils.PropertiesLoader;
import com.nervenets.web.controller.Global;
import com.nervenets.web.enumeration.PropertyName;
import com.nervenets.web.filter.CORSFilter;
import com.nervenets.web.hibernate.dao.UserDao;
import com.nervenets.web.hibernate.domain.Property;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.hibernate.domain.user.UserRole;
import com.nervenets.web.rabbitmq.MessageProducer;
import com.nervenets.web.redis.GlobalService;
import com.nervenets.web.redis.GlobalVariablesService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.weixin4j.Weixin;
import org.weixin4j.WeixinUrlFilter;
import org.weixin4j.http.OAuthToken;

import javax.annotation.Resource;

/**
 * Created by Joe on 2018/1/8.
 */
@Configuration
public class ApplicationConfiguration implements InitializingBean {
    @Resource
    GlobalService globalService;
    @Resource
    GlobalVariablesService globalVariablesService;
    @Resource
    UserDao userDao;
    @Resource
    PropertiesLoader configProperties;
    @Resource
    MessageProducer messageProducer;

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("检查系统初始化数据...");
        Property systemInitialize = userDao.getProperty(PropertyName.SYSTEM_INITIALIZE, false);
        if (!"true".equals(systemInitialize.toString())) {
            System.out.println("开始初始化系统基本参数...");
            initializeSystemAccount();
            System.out.println("结束初始化系统基本参数...");
            systemInitialize.setValue("true");
            userDao.saveOrUpdate(systemInitialize);
        }

        //暂停生成测试用户
        /*int userId = 0;
        for (int i = 0; i < NumberUtil.randomNumber(15, 30); i++) {
            userId = testDataSet(userId);
        }*/

        try {
            Weixin weixin = Global.getWeixin();
            OAuthToken weChatAuthToken = globalVariablesService.getWeChatAuthToken();
            if (null == weChatAuthToken) {
                weixin.reLogin();
                globalVariablesService.setWeChatAuthToken(weixin.getOAuthToken());
            } else {
                weixin.setOauthToken(weChatAuthToken);
            }
            System.out.println("微信登录成功！");
            System.out.println(globalVariablesService.getWeChatAuthToken());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initializeSystemAccount() {
        String defaultUsername = configProperties.getProperty("app.default.administrator");
        String defaultPassword = configProperties.getProperty("app.default.administrator_password");
        System.out.println("查询并设置系统默认管理账号:" + defaultUsername + ",密码:" + defaultPassword);

        User user = userDao.getUserByMobile(defaultUsername);
        if (user == null) {
            user = new User(defaultUsername, defaultPassword);
            user.setCode("888888");
            user.getInfo().setName("管理员");
            user.setRole(UserRole.admin());
            userDao.saveOrUpdate(user);
        }
        globalService.clearRedis();
    }

    @Bean
    public FilterRegistrationBean wechatUrlFilterBean() {
        FilterRegistrationBean wechatUrlFilterBean = new FilterRegistrationBean();
        wechatUrlFilterBean.setFilter(new WeixinUrlFilter());
        wechatUrlFilterBean.addUrlPatterns("/api/weixin4j");
        return wechatUrlFilterBean;
    }

    @Bean
    public FilterRegistrationBean corsFilterBean() {
        FilterRegistrationBean corsFilterBean = new FilterRegistrationBean();
        corsFilterBean.setFilter(new CORSFilter());
        corsFilterBean.addUrlPatterns("/*");
        return corsFilterBean;
    }
}
